Param(
  [Parameter(Mandatory = $true)] [string]$InPath,  # video file or folder containing videos
  [string]$OutRoot = '.',                          # output root (local or NAS-mapped path)
  [int]$Fps = 3,
  [int]$ScaleH = 720,
  [int]$Quality = 2,                               # JPEG quality (2=high, 31=low)
  [string]$Owner = $env:USERNAME,
  [string]$Location = '',
  [string]$TimeOfDay = '',
  [string]$Weather = '',
  [string]$Notes = ''
)

function Require-Tool($name) {
  $exists = (Get-Command $name -ErrorAction SilentlyContinue) -ne $null
  if (-not $exists) {
    Write-Error ("Missing dependency: {0}. Please install and ensure it is in PATH." -f $name)
    exit 1
  }
}

Require-Tool 'ffmpeg'

$videoExt = @('*.mp4','*.mov','*.mkv','*.avi')

function Get-VideoList($path) {
  if (Test-Path $path -PathType Leaf) { return ,(Get-Item $path) }
  elseif (Test-Path $path -PathType Container) { return Get-ChildItem -Recurse -File -Include $videoExt -Path $path }
  else { Write-Error ("Path not found: {0}" -f $path); exit 1 }
}

$videos = Get-VideoList $InPath
if ($videos.Count -eq 0) { Write-Warning ("No videos found. Supported: {0}" -f ($videoExt -join ', ')); exit 0 }

Write-Host ("Found videos: {0}. OutRoot: {1}`nArgs: FPS={2}, ScaleH={3}, JPEG Q={4}" -f $videos.Count, $OutRoot, $Fps, $ScaleH, $Quality) -ForegroundColor Cyan

foreach ($v in $videos) {
  $name = [System.IO.Path]::GetFileNameWithoutExtension($v.FullName)
  $outDir = Join-Path $OutRoot $name
  New-Item -ItemType Directory -Force -Path $outDir | Out-Null

  $vf = "fps=$Fps,scale=-2:$ScaleH"
  $outPattern = Join-Path $outDir '%06d.jpg'

  Write-Host ("Extracting frames: {0}" -f $name) -ForegroundColor Green
  $ffargs = @('-y','-hwaccel','auto','-i', $v.FullName, '-vf', $vf, '-q:v', $Quality, $outPattern)
  $proc = Start-Process -FilePath ffmpeg -ArgumentList $ffargs -NoNewWindow -PassThru -Wait
  if ($proc.ExitCode -ne 0) { Write-Warning ("ffmpeg failed: {0}" -f $v.FullName); continue }

  $jpgs = Get-ChildItem -File -Filter *.jpg -Path $outDir
  $count = $jpgs.Count
  if ($count -eq 0) { Write-Warning ("No JPGs generated: {0}" -f $name); continue }

  # write meta.csv in each folder
  $metaPath = Join-Path $outDir 'meta.csv'
  $date = Get-Date -Format 'yyyy-MM-dd'
  $header = "video_id,fps_extract,scale_h,frame_count,owner,date,location,time_of_day,weather,notes"
  $row =  ("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}" -f $name,$Fps,$ScaleH,$count,$Owner,$date,$Location,$TimeOfDay,$Weather,$Notes)
  Set-Content -LiteralPath $metaPath -Value ($header + "`n" + $row + "`n") -Encoding UTF8

  Write-Host ("Done: {0}, frames={1}, meta={2}" -f $name, $count, $metaPath) -ForegroundColor Yellow
}

Write-Host "All done. Upload each <video_id>/ folder to NAS share: \\NAS\\Yolo训练集\\03_frames_raw\\<video_id>" -ForegroundColor Cyan
